// schema扩展相关文档请参阅：https://uniapp.dcloud.net.cn/uniCloud/jql-schema-ext.html
const db = uniCloud.database();
module.exports = {   
    trigger: {
		async beforeRead({clientInfo,where}){
			// console.log('where',where);
			const {conversation_id} = where
			if(conversation_id){
				// console.log('conversation_id',conversation_id);
				const dbJQL = uniCloud.databaseForJQL({
					clientInfo,
					skipTrigger: true
				})
				
				//判断当前用户id是否有这个会话，否则无权接收此消息
				let {data:conversations} = await dbJQL.collection('uni-im-conversation')
													.where(`"id" == "${conversation_id}" && "user_id" == $cloudEnv_uid`)
													.get()
				// console.log('conversations',conversations);
				if(conversations.length === 0){
					throw new Error('会话id无效，或此会话你无权服务，即：user_id不等于当前用户')
				}
				// if(conversations[0].type == 2){ //2是群聊
				// 	let {group_id} = conversations[0]
				// 	let res = await dbJQL.collection('uni-im-group-member')
				// 						.where(`"group_id" == "${group_id}" && "user_id" == $cloudEnv_uid`)
				// 						.get()
				// 	if(res.data.length == 0){
				// 		throw new Error('不是此群人员，不能读取')
				// 	}
				// }
			}else{
				throw new Error('触发器限制了只能通过，会话id查询。如果要增加其他查询方式，请自己扩充')
			}
		}
    }
}
